/**
 * @ProjectName： naive-admin
 * @FileName： user
 * @Description: // 用户信息封装
 * @Author: ellwood
 * @date: 2024/1/18 - 7:43
 * @Version: V1.0.0
 */
import type { RouteRecordRaw } from 'vue-router'
import type { UserInfo } from '@/api/model/user.ts'
import type { UserMobileLoginParams } from '@/api/params/MobileLoginParams.ts'
import type { UserAccountLoginParams } from '@/api/params/AccountLoginParams.ts'
import { userGetInfoApi, userLoginApi } from '@/api/userApi.ts'
import router from '~/router'
import i18n from '@/locales'
import { dynamicRoutes, rootRouter } from '~/router/dynamicRoutes.ts'
import { flatRoutes, generateRoute } from '@/router/generate-route.ts'
import { generateMenu } from '~/router/generate-menu.ts'

const useUserStore = defineStore('user', () => {
  const userInfo = ref<UserInfo>()

  const token = useAuthorization()

  const t = i18n.global.t
  const { message } = useGlobalConfig()

  const routerRecords = ref<RouteRecordRaw[]>()

  const menusData = computed(() => generateMenu(routerRecords.value ?? []))
  const setUserInfo = (info: UserInfo | undefined) => {
    userInfo.value = info
  }

  const setToken = (key: string | null) => {
    token.value = key
  }

  const login = async (
    params: UserMobileLoginParams | UserAccountLoginParams,
  ) => {
    const { data } = await userLoginApi(params)
    if (data?.token)
      setToken(data.token)
  }

  const getUserInfo = async () => {
    const { data } = await userGetInfoApi()
    if (data)
      setUserInfo(data)
  }

  const logout = async () => {
    setToken(null) // 退出清空token
    setUserInfo(undefined) // 退出清空用户信息
    message?.success(t('global.layout.header.right.logout.success'), {
      duration: 3000,
    })
    await router.replace({
      path: '/logout',
      query: {
        redirect: router.currentRoute.value.path,
      },
    })
  }

  /**
   * 静态路由
   */
  const generateRouter = async () => {
    const flatRouteData = flatRoutes(dynamicRoutes)
    const currentRouter = {
      ...rootRouter,
      children: [flatRouteData],
    }
    routerRecords.value = dynamicRoutes

    return currentRouter
  }

  /**
   * 动态路由
   */
  const generateDynamicRoutes = async () => {
    const routerData = await generateRoute()
    if (routerData) {
      routerRecords.value = routerData.children
      const flatRouteData = flatRoutes(routerData.children)
      routerData.children = [flatRouteData]
    }

    return routerData
  }

  return {
    userInfo,
    setUserInfo,
    setToken,
    login,
    getUserInfo,
    logout,
    menusData,
    routerRecords,
    generateRouter,
    generateDynamicRoutes,
  }
})

export { useUserStore }
